Penalty.stats = {};
Penalty.stats.map = {};

Penalty.stats.labels = {
  won:'Won', 
  lost:'Lost', 
  goals:'Goals', 
  blocks:'Saves', 
  shoots:'Shoots', 
  block_attempts:'Save attempts'
};

Penalty.stats.load = function() {
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonAppDataRequest('OWNER', 'stats'), 'myStats');
  req.send(function(response){
    var data = response.get('myStats').getData();
    if (!data) return;
    for (var i in data) {
      Penalty.stats.map = gadgets.json.parse(data[i].stats);
    }
  });
}

Penalty.stats.save = function() {
  var req = opensocial.newDataRequest();
  req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'stats', gadgets.json.stringify(Penalty.stats.map)));
  req.send(function(response){
    log('stats.save() response:' + response.hadError().toString());
  });
}

Penalty.stats.updateInternal = function(id, action, result) {
  if (!Penalty.stats.map[id]) {
    Penalty.stats.map[id] = {won:0, lost:0, goals:0, blocks:0, shoots:0, block_attempts:0};
  }
  if (result == 'WON') {
    Penalty.stats.map[id].won++;
    if (action == 'SHOOT') {
      Penalty.stats.map[id].goals++;
    } else {
      Penalty.stats.map[id].blocks++;
    }
  } else {
    Penalty.stats.map[id].lost++;
  }
  if (action == 'SHOOT') {
    Penalty.stats.map[id].shoots++;
  } else {
    Penalty.stats.map[id].block_attempts++;
  }
}

Penalty.stats.update = function(id, action, result) {
  Penalty.stats.updateInternal(id, action, result);
  Penalty.stats.updateInternal('GLOBAL', action, result);
}

Penalty.stats.getShootingEP = function(){
  if (Penalty.stats.map['GLOBAL'].shoots == 0) {
    return 0;
  }
  var percent = Penalty.stats.map['GLOBAL'].goals / Penalty.stats.map['GLOBAL'].shoots * 100;
  return '' + Math.round(percent) + '%';  
}

Penalty.stats.getBlockingEP = function(){
  if (Penalty.stats.map['GLOBAL'].block_attempts == 0) {
    return 0;
  }
  var percent = Penalty.stats.map['GLOBAL'].blocks / Penalty.stats.map['GLOBAL'].block_attempts * 100;
  return '' + Math.round(percent) + '%';  
}

Penalty.stats.getHistoricStats = function(id) {
  return Penalty.stats.map[id];
}

Penalty.stats.getGlobalStats = function() {
  return Penalty.stats.map['GLOBAL'];
}

Penalty.stats.getHistoricStatsString = function(id) {
  return Penalty.stats.map[id] ? 
      '(You have won ' + Penalty.stats.map[id].won + ' times and lost ' + Penalty.stats.map[id].lost + ' times against him)' 
      : '(You never played against him)';
}

Penalty.stats.getGlobalStatsString = function(id) {
  return Penalty.stats.map['GLOBAL'] ? 
      '[Overall Stats] Challenges Won: ' + Penalty.stats.map['GLOBAL'].won + '. Challenges Lost: ' + Penalty.stats.map['GLOBAL'].lost 
      : '[No overall stats yet]';
}

Penalty.stats.clearStats = function() {
  var req = opensocial.newDataRequest();
  req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'stats', {}));
  req.send(function(response){
    log('clear stats response:' + response.hadError().toString());
  });
}

Penalty.stats.createGlobalStatsNode = function(viewer){
  if (!Penalty.stats.map['GLOBAL']) {
    return document.createElement('div');
  }
  var tbody = document.createElement('tbody');
  var table = document.createElement('table');
  table.border = 2;
  table.width = '600px';
  table.class = 'table';
  table.appendChild(tbody);
  
  var header = document.createElement('tr');
  tbody.appendChild(header);
  var nameLabel = document.createElement('td');
  nameLabel.innerHTML = (!viewer) ? '<b>Your global stats:</b>' : '<b>' + Penalty.me.getDisplayName() + '\'s global stats:</b>';
  header.appendChild(nameLabel);
  
  // headers
  for (var label in Penalty.stats.getGlobalStats()) { 
    var th = document.createElement('td');
    header.appendChild(th);
    th.innerHTML = '<b>' + Penalty.stats.labels[label] + '</b>';
  }

  // only row
  var tr = document.createElement('tr');
  var stats = Penalty.stats.getGlobalStats();
  tbody.appendChild(tr);
  
  //set Totals as first column
  var name = document.createElement('td');
  name.innerHTML = 'Totals';
  tr.appendChild(name);
  
  //set rest of the stats columns
  for (var stat in stats) {
    var td = document.createElement('td');  
    tr.appendChild(td);
    td.innerHTML = stats[stat];
  }
  return table;
}


Penalty.stats.createTableNode = function(viewer){
  if (!Penalty.stats.map['GLOBAL']) {
    return document.createElement('div');
  }
  var tbody = document.createElement('tbody');
  var table = document.createElement('table');
  table.width = '600px';
  table.class = 'table';
  table.border = 2;
  table.appendChild(tbody);

  if (Penalty.stats.map['GLOBAL']) {
    var header = document.createElement('tr');
    tbody.appendChild(header);
    var nameLabel = document.createElement('td');
    nameLabel.innerHTML = (!viewer) ? '<b>Your stats vs friends:</b>' : '<b>' + Penalty.me.getDisplayName() + '\'s stats vs friends:</b>';
    header.appendChild(nameLabel);
  }
  
  for (var label in Penalty.stats.getHistoricStats('GLOBAL')) { 
    var th = document.createElement('td');
    header.appendChild(th);
    th.innerHTML = '<b>' + Penalty.stats.labels[label] + '</b>';
  }
    
  for (var id in Penalty.stats.map) {
    if (id != 'GLOBAL') {
      var tr = document.createElement('tr');
      var stats = Penalty.stats.getHistoricStats(id);
      tbody.appendChild(tr);
      
      //set name as first column
      var name = document.createElement('td');
      name.innerHTML = Penalty.friendsMap[id].getDisplayName();
      tr.appendChild(name);
      
      //set rest of the stats columns
      for (var stat in stats) {
        var td = document.createElement('td');  
        tr.appendChild(td);
        td.innerHTML = stats[stat];
      }
    }
  }
  return table;
}
